import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import rootReducer from '../reducers';

export default function configureStore(initialState) {
    const store = createStore(
        rootReducer,
        initialState,
        compose(
            // 为Redux添加日志中间件redux-logger。日志中间件可以打印程序运行过程中的action，以及action发起前后的state.
            // 大多数情况下，应该使用Redux开发者工具来追踪程序状态变化，
            // 此处使用日志中间件是为了在控制台中方便地看出组件生命周期函数的调用和action触发时机的时间先后关系。
            applyMiddleware(thunkMiddleware, createLogger()),
            window.devToolsExtension ? window.devToolsExtension() : f => f
        )
    );

    if (module.hot) {
        // Enable Webpack hot module replacement for reducers
        module.hot.accept('../reducers', () => {
            const nextRootReducer = require('../reducers').default;
            store.replaceReducer(nextRootReducer);
        });
    }

    return store;
}
